package com.jarvis.jarvischat.controller;


import cn.hutool.core.util.StrUtil;
import com.jarvis.common.utils.R;
import com.jarvis.jarvischat.feign.ConfigFeignService;
import com.jarvis.jarvischat.feign.UserFeignService;
import com.jarvis.jarvischat.vo.ConfigFormworkVo;
import com.jarvis.jarvischat.vo.UserVo;
import com.jarvis.jarvischat.vo.UserRecordVo;
import com.plexpt.chatgpt.ChatGPT;
import com.plexpt.chatgpt.entity.chat.ChatCompletion;
import com.plexpt.chatgpt.entity.chat.ChatCompletionResponse;
import com.plexpt.chatgpt.entity.chat.Message;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@Slf4j
public class ChatController {

    @Value("${chatgpt.apiKey}")
    private String apiKey;
    @Value("${chatgpt.apiHost}")
    private String apiHost;

    @Autowired
    private UserFeignService userFeignService;

    @Autowired
    private ConfigFeignService configFeignService;

    @RequestMapping("/chat")
    public R chat(@RequestParam("message") String msg, @RequestHeader Map<String, String> headers) {

        //首先判断是否存在这个用户
        String uid = headers.get("uid");
        if (StrUtil.isBlank(uid)) {
            return R.error(500,"服务器异常");
        }
        //获取用户
        UserVo userVo  = userFeignService.getUser(Long.parseLong(uid));
        if(checkIsVip(userVo) == false && checkHasFree(userVo) == false ) {
            return R.error(500,"您的免费次数已经用完");
        }

        ConfigFormworkVo formworkVo = new ConfigFormworkVo();

        List<Message> list = new ArrayList<Message>();
        Message message = Message.of(msg);
        list.add(message);
        ChatGPT chatGPT = ChatGPT.builder()
                .apiKey(apiKey)
                .timeout(900)
                .apiHost(apiHost) //反向代理地址
                .build()
                .init();
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                .messages(list)
                .maxTokens(3000)
                .temperature(0.9)
                .build();
        ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);
        reduceUserFreeCount(userVo);
        return R.ok().put("data",response);
    }



    @RequestMapping("/create")
    public R chat(@RequestParam("message") String msg,@RequestParam( required = false,value = "type") String type,@RequestParam(required = false,value = "words") String words, @RequestHeader Map<String, String> headers) {

        //首先判断是否存在这个用户
        String uid = headers.get("uid");
        if (StrUtil.isBlank(uid)) {
            return R.error(500,"服务器异常");
        }

        //获取用户
        UserVo userVo  = userFeignService.getUser(Long.parseLong(uid));
        if(checkIsVip(userVo) == false && checkHasFree(userVo) == false ) {
            return R.error(500,"您的免费次数已经用完");
        }
        ConfigFormworkVo formworkVo = configFeignService.getFormword(Long.parseLong(type));

        List<Message> list = new ArrayList<Message>();
        String str1 = "请以";
        String str2 = msg;
        String str3 = "为";
        String str4 = formworkVo.getKeyword();
        String str5 = "创作一篇";
        String str6 =  words;
        String str7 = "字的";
        String str8 = formworkVo.getTitle();
        String  messageStr = str1+str2+str3+str4+str5+str6+str7+str8;
        Message system = Message.ofSystem(formworkVo.getSystemcontent());
        Message message = Message.of(messageStr);
        list.add(system);
        list.add(message);

        ChatGPT chatGPT = ChatGPT.builder()
                .apiKey(apiKey)
                .timeout(900)
                .apiHost(apiHost) //反向代理地址
                .build()
                .init();
        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model(ChatCompletion.Model.GPT_3_5_TURBO.getName())
                .messages(list)
                .maxTokens(3000)
                .temperature(0.9)
                .build();
        ChatCompletionResponse response = chatGPT.chatCompletion(chatCompletion);

        Message res = response.getChoices().get(0).getMessage();
        //减少用户免费次数1次
        reduceUserFreeCount(userVo);
        return recordMessage(userVo,formworkVo,res.getContent(),words);
    }


    public R recordMessage(UserVo userVo, ConfigFormworkVo formworkVo, String result, String words) {

        if (formworkVo.getId() != null && words != null) {
            Date now = new Date();
            UserRecordVo recordVo = new UserRecordVo();
            recordVo.setUserId(userVo.getId());
            recordVo.setCreateContent(result);
            recordVo.setCreateType(formworkVo.getId().toString());
            recordVo.setCreateWords(words);
            recordVo.setCreateTitle(formworkVo.getTitle());
            recordVo.setCreateImage("");
            recordVo.setCreateTime(now);
            return userFeignService.save(recordVo);


        }else {
            return R.error(500,"创作失败");
        }
    }

    //检查会员
    public boolean checkIsVip(UserVo vo) {

        Date now = new Date();
        Date vipDate = vo.getEndTime();
        System.out.println("now:" + (now) + "vip:" + (vipDate));
        if (vipDate == null) {
            return false;
        }else {

            if (now.compareTo(vipDate) > 0) {
                return false;
            }else {
                return true;
            }
        }

    }

    //检查是否有免费次数
    public boolean checkHasFree(UserVo vo){
        System.out.println("剩余次数" + (vo.getFreecount()));
        return vo.getFreecount() > 0 ;
    }

    //调用成功后减少一次免费次数 会员另算
    public void reduceUserFreeCount(UserVo vo){

        //如果不是会员需要减一次免费次数
          if (checkIsVip(vo)==false){
              userFeignService.reduceFreeCount(vo.getId());
          }

    }










}

